<?php
namespace adminv1\auth; 
use adminv1\CoreController;
use Yii;
use admin\models\auth\User;
use admin\models\auth\Roles;

class ConnectController extends CoreController
{

	/*
		登录
		user_name 用户名
		password  密码
	*/
	public function actionLogin()
	{
		$userName = $this->request('username');
		$pass  = $this->request('password');
		$where = ['username' => $userName];
		$user  = User::getOne($where);
		if(!$user) return $this->error('用户不存在');
		if($user['password'] != md5($pass)) return $this->error('密码错误');

		//登录成功 成功auth_key
		$curTime = date("Y-m-d H:i:s");
		$authKey = User::generateAuthKey();
		$data  = array('auth_key' => $authKey);
		$data['username'] = $user['username'];
		$data['login_time'] = $curTime;
		$data['last_login_time'] = $user->login_time ? $user->login_time : $curTime;
		$data['avatar'] = $user['avatar'];

		if(!User::updateUserById($data, $user['id'])) return $this->error('登录失败');

		//获取用户权限
		$rulesTree = Roles::getRolesRulesTree($user['role_id'],1);
		$allRules = Roles::getRolesRules($user['role_id'], false, 1);
		
		$extend = array('rules_tree' => $rulesTree, 'rules' => $allRules);

		if(\Yii::$app->params['apiAuth']){
			$apiAuthData = Roles::getRolesApi($user['role_id']);
			$apiAuth = [];
			foreach($apiAuthData as $val){
				$apiAuth[] = $val['api_url'];
			}
			## 缓存起来
			\Yii::$app->cache->set('userApiCache_'.$user['id'], $apiAuth);
		}
		return $this->success('登录成功',$data,$extend);

	}
}
